package com.jyx.manage_media_process;

import com.alibaba.fastjson.JSON;
import com.jyx.framework.domain.media.MediaFile;
import com.jyx.framework.domain.media.MediaFileProcess_m3u8;
import com.jyx.framework.utils.HlsVideoUtil;

import com.jyx.manage_media_process.dao.MediaFileRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;

@SpringBootTest
@RunWith(SpringRunner.class)
public class UploadTest2 {
    @Value("${jyx-service-manage-media.ffmpeg-path}")
    String ffmpeg_path;
    @Value("${jyx-service-manage-media.upload-location}")
    String serverPath;
    @Autowired
    MediaFileRepository mediaFileRepository;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Test
    public void testChunk() throws IOException{
        String chunkPath = "F:/develop/media/chunk/";
        File sourseFile = new File("F:/develop/media/lucene.mp4");
        File chunkFolder = new File(chunkPath);
        if(!chunkFolder.exists()){
            chunkFolder.mkdirs();
        }
        //创建分块大小
        long chunkSize = 1024*1024*1;
        //计算分块数量
        long chunkNum = (long) Math.ceil(sourseFile.length()*1.0/chunkSize);
        //创建缓冲区大小
        byte[] b = new byte[1024];
        //RandomAccessFile访问
        RandomAccessFile raf_read = new RandomAccessFile(sourseFile,"r");
        //分块
        for (int i = 0; i < chunkNum; i++) {
            //创建分块文件
            File file = new File(chunkPath+i);
            boolean newFile = file.createNewFile();
            if(newFile){
                //向分块中写入文件
                RandomAccessFile raf_write = new RandomAccessFile(file,"rw");
                int len = -1;
                while((len = raf_read.read(b))!=-1){
                    raf_write.write(b,0,len);
                    if(file.length()>chunkSize){
                        break;
                    }
                }
                raf_write.close();
            }
        }
        raf_read.close();
    }

    @Test
    public void testMerge() throws IOException{
        File chunkFolder = new File("F:/develop/media/chunk/");
        File mergeFile = new File("F:/develop/media/lucene1.mp4");
        if(mergeFile.exists()){
            mergeFile.delete();
        }
        mergeFile.createNewFile();
        RandomAccessFile raf_write = new RandomAccessFile(mergeFile,"rw");
        raf_write.seek(0);
        byte[] b = new byte[1024];
        File[] fileArray = chunkFolder.listFiles();
        //转成集合，便于排序
        List<File> fileList = new ArrayList<File>(Arrays.asList(fileArray));
        //排序
        Collections.sort(fileList,new Comparator<File>(){
                    @Override
                    public int compare(File o1, File o2) {
                        if(Integer.parseInt(o1.getName())<Integer.parseInt(o2.getName())){
                            return -1;
                        }
                        return 1;
                    }
                });
        //合并
        for (File chunkFile:fileList) {
            RandomAccessFile raf_read = new RandomAccessFile(chunkFile, "rw");
            int len = -1;
            while((len=raf_read.read(b))!=-1) {
                raf_write.write(b, 0, len);
            }
            raf_read.close();
        }
        raf_write.close();
    }

    /**
     * 测试生成MP4
     * @throws IOException
     */
    @Test
    public void testMp4Utils() throws IOException{
        String mediaId = "5e9a6be15190ba35487d983c";
        Optional<MediaFile> mediaFileOptional = mediaFileRepository.findById(mediaId);
        if(!mediaFileOptional.isPresent()){
            System.out.println("当前id的媒体文件不存在~！");
            return;
        }
        Map<String, String> msgMap = new HashMap<>();
        msgMap.put("mediaId", mediaId);
        String msg = JSON.toJSONString(msgMap);
        System.out.println("开始发送消息。。。。"+msg);
        rabbitTemplate.convertAndSend("ex_media_processor","rountingkey_media_video",msg);
        System.out.println("发送成功~！");
       /* MediaFile mediaFile = mediaFileOptional.get();
        //1.先判断是否需要处理
        String fileType = mediaFile.getFileType();
        if(fileType == null || !fileType.equals("avi")){
            mediaFile.setFileStatus("303004");  //设置状态为无需处理
            mediaFileRepository.save(mediaFile);
        }else {
            mediaFile.setFileStatus("303001");  //设置状态为未处理
            mediaFileRepository.save(mediaFile);
        }
        //生成MP4
        String video_path = serverPath+mediaFile.getFilePath()+mediaFile.getFileName();
        String mp4_name = mediaFile.getFileId()+".mp4";
        String mp4FolderPath = serverPath + mediaFile.getFilePath();
        Mp4VideoUtil mp4VideoUtil = new Mp4VideoUtil(ffmpeg_path, video_path, mp4_name, mp4FolderPath);
        String result = mp4VideoUtil.generateMp4();
        if(result == null || !result.equals("success")){
            mediaFile.setFileStatus("303003"); //处理失败代码
            MediaFileProcess_m3u8 mediaFileProcess_m3u8 = new MediaFileProcess_m3u8();
            mediaFileProcess_m3u8.setErrormsg(result);
            mediaFile.setMediaFileProcess_m3u8(mediaFileProcess_m3u8);
            mediaFileRepository.save(mediaFile);
            return;
        }*/
    }

    @Test
    public void testRabbitReceiveMsg(){
        Object rountingkey_media_video = rabbitTemplate.receiveAndConvert("rountingkey_media_video");
        System.out.println(rountingkey_media_video.getClass());
        System.out.println(rountingkey_media_video);
    }

    @Test
    public void testM3u8Utils() throws IOException{
        String mediaId = "c5c75d70f382e6016d2f506d134eee11";
        Optional<MediaFile> mediaFileOptional = mediaFileRepository.findById(mediaId);
        if(!mediaFileOptional.isPresent()){
            System.out.println("当前id的媒体文件不存在~！");
            return;
        }
        MediaFile mediaFile = mediaFileOptional.get();
        //1.先判断是否需要处理
        String fileType = mediaFile.getFileType();
        if(fileType == null || !fileType.equals("avi")){
            mediaFile.setFileStatus("303004");  //设置状态为无需处理
            mediaFileRepository.save(mediaFile);
        }else {
            mediaFile.setFileStatus("303001");  //设置状态为未处理
            mediaFileRepository.save(mediaFile);
        }
        String video_path = serverPath + mediaFile.getFilePath() + mediaFile.getFileName();
        String m3u8_name = mediaId + ".m3u8";
        String m3u8FolderPath = serverPath+mediaFile.getFilePath()+"hls/";
        HlsVideoUtil hlsVideoUtil = new HlsVideoUtil(ffmpeg_path, video_path, m3u8_name, m3u8FolderPath);
        String result = hlsVideoUtil.generateM3u8();
        if(result == null || !result.equals("success")){
            System.out.println("处理失败~！");
            mediaFile.setFileStatus("303003"); //处理失败代码
            MediaFileProcess_m3u8 mediaFileProcess_m3u8 = new MediaFileProcess_m3u8();
            mediaFileProcess_m3u8.setErrormsg(result);
            mediaFile.setMediaFileProcess_m3u8(mediaFileProcess_m3u8);
            mediaFileRepository.save(mediaFile);
            return;
        }

    }
}
